import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import type { I18n, I18nOptions } from 'vue-i18n'
import { setHtmlPageLang } from './helper'

export let i18n: ReturnType<typeof createI18n>

// 动态导入指定语言的所有模块并合并
const importLanguageModules = async (lang: string) => {
  // 这里假设语言文件命名格式为：[lang].[module].ts
  // 例如：zh-CN.common.ts, en-US.menu.ts 等
  const modules = import.meta.glob('../../locales/**/*.ts', { eager: true })

  const messages: Record<string, any> = {}

  Object.keys(modules).forEach((path) => {
    // 检查路径是否匹配当前语言
    if (path.includes(`/${lang}.`)) {
      const module = modules[path] as { default: Record<string, any> }
      // 直接合并到messages对象中，不保留模块名
      Object.assign(messages, module.default)
    }
  })

  return messages
}
const createI18nOptions = async (): Promise<I18nOptions> => {
  const localeStore = useLocaleStoreWithOut()
  const locale = localeStore.getCurrentLocale
  const localeMap = localeStore.getLocaleMap
  const message =  await importLanguageModules(locale.lang) ?? {}

  setHtmlPageLang(locale.lang)

  localeStore.setCurrentLocale({
    lang: locale.lang
    // elLocale: elLocal
  })

  return {
    legacy: false,
    locale: locale.lang,
    fallbackLocale: locale.lang,
    messages: {
      [locale.lang]: message
    },
    availableLocales: localeMap.map((v) => v.lang),
    sync: true,
    silentTranslationWarn: true,
    missingWarn: false,
    silentFallbackWarn: true
  }
}

export const setupI18n = async (app: App<Element>) => {
  const options = await createI18nOptions()
  i18n = createI18n(options) as I18n
  app.use(i18n)
}
